<template>
  <el-dialog v-if="load" :close-on-click-modal="false" title="修改产品信息" class="full" v-model="visible" align-center
    :z-index="2000" width="800px" @close="handleClose">
    <el-form ref="formRef" :model="form" label-position="top">
      <div class="grid grid-cols-3 gap-x-3">
        <el-form-item label="供应商名称" prop="supplier_id" :rules="[{ required: true, message: '不能为空', trigger: 'change' }]">
          <VSelect v-model="form.supplier_id" type="supplier" placeholder="请输入" filterable clearable class="w-full"
            @change="({ option }) => (form.supplier_name = option.label)" />
        </el-form-item>
        <el-form-item label="采购链接">
          <el-input v-model="form.goods_link" placeholder="采购链接" class="w-full" />
        </el-form-item>
        <el-form-item label="是否默认供应商" :rules="[{ required: true, message: '不能为空', trigger: 'blur' }]">
          <VSelect v-model="form.is_default_supplier" :options="options.default_supplier || []" placeholder="请输入"
            class="w-full" />
        </el-form-item>
        <el-form-item label="采购未税价">
          <template #label>
            <div class="inline-flex items-center">
              <span class="inline items-center leading-[20px]">采购未税价</span>
              <el-tooltip effect="dark" raw-content content="1、采购未税价=采购含税价/（1+发票税点），四舍五入保留两位小数。<br/>
                     2、发票税点默认：13，支持调整。<br/>
                     3、维护采购含税价、发票税点，系统将自动计算采购未税价。<br/>" placement="top">
                <i class="dk-iconfont icon-QuestionFilled ml-[4px] relative cursor-pointer text-sm" />
              </el-tooltip>
            </div>
          </template>
          <VGroup>
            <el-input-number v-model="form.purchase_untaxed_price" :controls="false" :min="0" :step="0.01" :precision="2"
              disabled class="w-full" />
            <div class="v-group-item el-input-group__append rounded-r-sm">CNY</div>
            <div class="ml-2">=</div>
          </VGroup>
        </el-form-item>
        <el-form-item label="采购含税价">
          <VGroup>
            <el-input-number v-model="form.price_include_tax" :controls="false" :min="0" :step="0.01" :precision="2"
              disabled class="w-full" />
            <span class="v-group-item el-input-group__append rounded-r-sm">CNY</span>
            <div class="ml-2">/</div>
          </VGroup>
        </el-form-item>
        <el-form-item label="发票税点">
          <div class="flex items-center gap-2">
            <span class="whitespace-nowrap">(1+</span>
            <VGroup>
              <el-input-number v-model="form.invoice_tax_rate" :controls="false" :min="0" :step="0.01" :precision="2"
                class="w-full" @blur="calculatePrice" />
              <span class="v-group-item el-input-group__append rounded-r-sm">%</span>
            </VGroup>
            <span class="whitespace-nowrap">)</span>
          </div>
        </el-form-item>
        <el-form-item label="采购未税报价" prop="price_exclude_tax"
          :rules="[{ required: true, message: '不能为空', trigger: 'change' }]">
          <template #label>
            <div class="inline-flex items-center">
              <span class="inline items-center leading-[20px]">采购未税报价</span>
              <el-tooltip effect="dark" raw-content content="1、采购未税报价，原供应商报价（不含税）<br/>
                      2、采购含税价，原供应商报价（含税）<br/>
                      3、采购未税报价=采购含税价/（1+供应商税点），四舍五入保留两位小数<br/>
                      4、采购未税报价、采购含税价、供应商税点，三者填写中两项，自动计算第三个字段。" placement="top">
                      <i class="dk-iconfont icon-QuestionFilled ml-[4px] relative cursor-pointer text-sm" />
              </el-tooltip>
            </div>
          </template>
          <VGroup>
            <el-input-number v-model="form.price_exclude_tax" :controls="false" :min="0" :step="0.01" :precision="2"
              class="w-full" @blur="blurcalculate()" @change="changecalculate('price_exclude_tax')" />
            <div class="v-group-item el-input-group__append rounded-r-sm">CNY</div>
            <div class="ml-2">=</div>
          </VGroup>
        </el-form-item>
        <el-form-item label="采购含税价">
          <VGroup>
            <el-input-number v-model="form.price_include_tax" :controls="false" :min="0" :step="0.01" :precision="2"
              class="w-full" @blur="blurcalculate()" @change="changecalculate('price_include_tax')" />
            <span class="v-group-item el-input-group__append rounded-r-sm">CNY</span>
            <div class="ml-2">/</div>
          </VGroup>
        </el-form-item>
        <el-form-item label="供应商税点" prop="tax_rate" :rules="[{ required: true, message: '不能为空', trigger: 'change' }]">
          <div class="flex items-center gap-2">
            <span class="whitespace-nowrap">(1+</span>
            <VGroup>
              <el-input-number v-model="form.tax_rate" :controls="false" :min="0" :step="0.01" :precision="2"
                class="w-full" @blur="blurcalculate()" @change="changecalculate('tax_rate')" />
              <span class="v-group-item el-input-group__append rounded-r-sm">%</span>
            </VGroup>
            <span class="whitespace-nowrap">)</span>
          </div>
        </el-form-item>
        <el-form-item label="最新起订量/MOQ">
          <el-input-number v-model="form.min_order_quantity" controls-position="right" :min="1" :step="1" :precision="0"
            class="w-full" />
        </el-form-item>
        <el-form-item label="采购天数" class="col-span-2">
          <div class="flex items-center gap-2">
            <el-input :value="form.product_day + form.transport_day + form.storage_day" disabled class="w-20"></el-input>
            <span>=</span>
            <el-input-number v-model="form.product_day" controls-position="right" :min="0" :step="1" :precision="0"
              class="w-28" placeholder="生产天数" />
            <span>+</span>
            <el-input-number v-model="form.transport_day" controls-position="right" :min="0" :step="1" :precision="0"
              class="w-28" placeholder="采购运输天数" />
            <span>+</span>
            <el-input-number v-model="form.storage_day" controls-position="right" :min="0" :step="1" :precision="0"
              class="w-28" placeholder="入库天数" />
          </div>
        </el-form-item>
        <el-form-item label="是否备料">
          <VSelect v-model="form.is_demand" placeholder="请选择" :options="options.is_demand" class="w-full" />
        </el-form-item>
        <el-form-item label="备料后采购天数" class="col-span-2">
          <div class="flex items-center gap-2">
            <el-input :value="form.prepare_product_day + form.prepare_shipping_day + form.prepare_arrived_day" disabled
              class="w-20"></el-input>
            <span>=</span>
            <el-input-number v-model="form.prepare_product_day" controls-position="right" :min="0" :step="1"
              :precision="0" class="w-28" placeholder="生产天数" />
            <span>+</span>
            <el-input-number v-model="form.prepare_shipping_day" controls-position="right" :min="0" :step="1"
              :precision="0" class="w-28" placeholder="采购运输天数" />
            <span>+</span>
            <el-input-number v-model="form.prepare_arrived_day" controls-position="right" :min="0" :step="1"
              :precision="0" class="w-28" placeholder="入库天数" />
          </div>
        </el-form-item>
        <el-form-item label="是否退税" prop="is_refund_tax" :rules="[{ required: true, message: '不能为空', trigger: 'change' }]">
          <VSelect v-model="form.is_refund_tax" placeholder="请选择" :options="options.is_refund_tax" class="w-full" />
        </el-form-item>
        <el-form-item label="中文报关名称" prop="chinese_customs_name"
          :rules="[{ required: true, message: '不能为空', trigger: 'blur' }]">
          <el-input v-model="form.chinese_customs_name" placeholder="中文报关名称" class="w-full" />
        </el-form-item>
        <el-form-item label="英文报关名称" prop="english_customs_name"
          :rules="[{ required: true, message: '不能为空', trigger: 'blur' }]">
          <el-input v-model="form.english_customs_name" placeholder="英文报关名称" class="w-full" />
        </el-form-item>
        <el-form-item label="产品用途">
          <el-input v-model="form.product_use" placeholder="产品用途" class="w-full" />
        </el-form-item>
        <el-form-item label="中文报关材质" prop="chinese_customs_material"
          :rules="[{ required: true, message: '不能为空', trigger: 'blur' }]">
          <el-input v-model="form.chinese_customs_material" placeholder="中文报关材质" class="w-full" />
        </el-form-item>
        <el-form-item label="英文报关材质" prop="english_customs_material"
          :rules="[{ required: true, message: '不能为空', trigger: 'blur' }]">
          <el-input v-model="form.english_customs_material" placeholder="英文报关材质" class="w-full" />
        </el-form-item>
      </div>
      <div class="grid grid-cols-2 gap-x-3">
        <el-form-item label="海关编码" prop="customs_code" :rules="[{ required: true, message: '不能为空', trigger: 'blur' }]">
          <div class="flex w-full">
            <el-input v-model="form.customs_code" placeholder="海关编码" class="w-full" />
            <el-button link type="primary" class="ml-2">
              <a target="_blank"
                :href="form.customs_code ? `http://www.hsbianma.com/search?keywords=${form.customs_code}` : 'http://www.hsbianma.com/Home/Message'">点击进入海关编码查询</a>
            </el-button>
          </div>
        </el-form-item>
        <el-form-item label="退税率">
          <VGroup class="w-full">
            <el-input-number v-model="form.tax_refund_rate" :controls="false" :min="0" :step="0.01" :precision="2"
              placeholder="请输入" class="w-full" />
            <span class="v-group-item el-input-group__append rounded-r-sm">%</span>
          </VGroup>
        </el-form-item>
        <el-form-item label="报关价">
          <VGroup class="w-full">
            <el-input-number v-model="form.customs_price" :controls="false" :min="0" :step="0.01" :precision="2"
              placeholder="请输入" class="w-full" />
            <span class="v-group-item el-input-group__append rounded-r-sm">USD</span>
          </VGroup>
          <div>（保留两位小数，默认是供货价的40%，转换为美元）</div>
        </el-form-item>
        <el-form-item label="报关单位" prop="customs_unit" :rules="[{ required: true, message: '不能为空', trigger: 'blur' }]">
          <VGroup class="w-full">
            <el-input v-model="form.customs_unit" placeholder="报关单位" class="w-full" />
            <span class="v-group-item el-input-group__append rounded-r-sm">（举例：个、套、台）</span>
          </VGroup>
        </el-form-item>
        <el-form-item label="报关链接" class="col-span-2">
          <div class="flex w-full">
            <el-input v-model="form.customs_link" placeholder="报关链接" />
            <el-button link type="primary" class="ml-2">
              <a target="_blank" :href="form.customs_link">打开报关链接</a>
            </el-button>
          </div>
        </el-form-item>
        <el-form-item label="报关链接价格" class="col-span-2">
          <VGroup>
            <el-input-number v-model="form.customs_link_price" :controls="false" :min="0" :step="0.01" :precision="2"
              placeholder="请输入" class="w-96" />
            <span class="v-group-item el-input-group__append rounded-r-sm">EUR</span>
          </VGroup>
          <div class="text-sm whitespace-nowrap mt-1">（保留两位小数，默认报关价格根据汇率转换成欧元，低于10欧的默认加2欧作为运费）</div>
        </el-form-item>
      </div>
      <el-form-item label="申报要素">
        <el-input v-model="form.declare_element" type="textarea" :autosize="{ minRows: 2, maxRows: 5 }" placeholder="申报要素"
          class="w-full" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="close">取 消</el-button>
      <el-button type="primary" :loading="loadings.create" @click="create(formRef)">确 定</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import api from '../api'
import { supplier } from '@/api/public'
import { ElMessage } from 'element-plus'
import XEUtils from 'xe-utils'
const props = defineProps({
  options: { type: Object, default: () => ({}) },
})
const emit = defineEmits(['close', 'success'])

const load = ref(false)
const visible = ref(false)
let loadings = reactive({})
const tableRef = ref()

// 表单处理
const formRef = ref()
const form = ref({})

const blurcalculate = () => {
  const { price_include_tax, tax_rate, price_exclude_tax } = form.value;
  if (price_include_tax && tax_rate && !price_exclude_tax) {
    form.value.price_exclude_tax = (Number(form.value.price_include_tax) / (1 + (form.value.tax_rate / 100))).toFixed(2)
  } else if (price_include_tax && !tax_rate && price_exclude_tax) {
    form.value.tax_rate = (((Number(form.value.price_include_tax) - Number(form.value.price_exclude_tax)) / Number(form.value.price_exclude_tax)) * 100).toFixed(2)
  } else if (!price_include_tax && tax_rate && price_exclude_tax) {
    form.value.price_include_tax = (Number(form.value.price_exclude_tax) * (1 + (form.value.tax_rate / 100))).toFixed(2)
  }
  calculatePrice()
}

const changecalculate = (field) => {
  let flage = ['price_include_tax', 'tax_rate', 'price_exclude_tax']
  const { price_include_tax, tax_rate, price_exclude_tax } = form.value;
  if (price_include_tax && price_include_tax != 0 && tax_rate && tax_rate != 0 && price_exclude_tax && price_exclude_tax != 0) {
    flage?.forEach(flag => {
      if (flag !== field) form.value[flag] = null;
    });
  }
}
const calculatePrice = () => {
  form.value.purchase_untaxed_price = (form.value.price_include_tax / (1 + (form.value.invoice_tax_rate / 100))).toFixed(2)
  // }
  // if (!form.value.invoice_tax_rate || form.value.invoice_tax_rate == '0.00') {
  //   form.value.purchase_untaxed_price = 0
  // } else if (form.value.price_include_tax) {
  //   form.value.purchase_untaxed_price = (form.value.price_include_tax / (1 + (form.value.invoice_tax_rate / 100))).toFixed(2)
  // }
}

// 打开弹窗
const open = async (id) => {
  if (!load.value) {
    load.value = true
    await 1
  }
  const res = await api.detail({ p_ids: id })
  form.value = res.data[0]
  if (form.value.is_default_supplier === 0) {
    form.value.is_default_supplier = 2
  }
  loadings = reactive({})
  visible.value = true
}
// 关闭弹窗
const close = () => {
  visible.value = false
}

const handleClose = () => {
  emit('close')
}

// 提交
const create = async (formRef) => {
  const validator = await formRef.validate()
  if (!validator) return
  loadings.create = true
  form.value.purchase_day = form.value.product_day + form.value.transport_day + form.value.storage_day
  form.value.prepare_purchase_day = form.value.prepare_product_day + form.value.prepare_shipping_day + form.value.prepare_arrived_day
  api[form.value.p_id ? 'edit' : 'create'](form.value).then(res => {
    ElMessage.success('保存成功')
    emit('success')
    close()
  }).finally(() => {
    loadings.create = false
  })
}

defineExpose({ open })
</script>